package com.example.demo.utils;

import com.auth0.jwt.JWT;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/*
    解析用户凭证
 */
public class JWTUtils {

    /**
     * 获取用户id
     * @param request 请求对象
     * @return
     */
    public static Long getUserIdByAud(HttpServletRequest request){
        String token = request.getHeader("token");
        return Long.valueOf(JWT.decode(token).getAudience().get(0));
    }

    /**
     * 获取用户账号
     * @param request 请求对象
     * @return
     */
    public static String getUsernameByClaim(HttpServletRequest request){
        String token = request.getHeader("token");
        return JWT.decode(token).getClaim("username").asString();
    }

    /**
     * 获取用户id
     * @param request 请求对象
     * @return
     */
    public static Long getUserIdByClaim(HttpServletRequest request){
        String token = request.getHeader("token");
        return JWT.decode(token).getClaim("userId").asLong();
    }
    /**
     * 获取用户id
     * @return
     */
    public static Long getUserIdByAud(){
        HttpServletRequest request = getServletRequestAttributes().getRequest();
        String token = request.getHeader("token");
        return Long.valueOf(JWT.decode(token).getAudience().get(0));
    }

    /**
     * 获取用户账号
     * @return
     */
    public static String getUsernameByClaim(){
        HttpServletRequest request = getServletRequestAttributes().getRequest();
        String token = request.getHeader("token");
        return JWT.decode(token).getClaim("username").asString();
    }

    /**
     * 获取用户id
     * @return
     */
    public static Long getUserIdByClaim(){
        HttpServletRequest request = getServletRequestAttributes().getRequest();
        String token = request.getHeader("token");
        return JWT.decode(token).getClaim("userId").asLong();
    }

    /**
     *  RequestAttributes : 存储当前请求中所有的数据信息 - 存储至线程中
     * @return
     */
    public static RequestAttributes getRequestAttributes(){
        return RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取 ServletRequestAttributes
     * @return
     */
    public static ServletRequestAttributes getServletRequestAttributes(){
        return (ServletRequestAttributes) getRequestAttributes();
    }

}
